using System;
using System.Collections.Generic;
using System.Text;
using System.Web;
using WCSFContrib.PageFlow.Xml.Properties;

namespace WCSFContrib.PageFlow.Xml.Storage.Session
{
    public class XmlPageFlowInstanceSessionStore : IXmlPageFlowInstanceStore
    {
        private const string XmlPageFlowInstanceSessionStoreKey = "XmlPageFlowInstanceSessionStore";

        protected virtual Dictionary<Guid, XmlPageFlowInstance> Instances
        {
            get
            {
                HttpContext context = HttpContext.Current;
                if (context == null)
                    throw new InvalidOperationException(Resources.HttpContextNotAvailable);

                Dictionary<Guid, XmlPageFlowInstance> instances = context.Session[XmlPageFlowInstanceSessionStoreKey] as Dictionary<Guid, XmlPageFlowInstance>;
                if (instances == null)
                {
                    instances = new Dictionary<Guid, XmlPageFlowInstance>();
                    context.Session[XmlPageFlowInstanceSessionStoreKey] = instances;
                }
                return instances;
            }
        }

        #region IXmlPageFlowInstanceStore Members

        public void Add(XmlPageFlowInstance instance)
        {
            this.Instances.Add(instance.InstanceId, instance);
        }

        public void Remove(Guid instanceId)
        {
            this.Instances.Remove(instanceId);
        }

        public XmlPageFlowInstance Get(Guid instanceId)
        {
            Dictionary<Guid, XmlPageFlowInstance> instances = this.Instances;
            if (instances.ContainsKey(instanceId))
            {
                return instances[instanceId];
            }
            return null;
        }

        public void Update(XmlPageFlowInstance instance)
        {
            this.Instances[instance.InstanceId] = instance;
        }

        #endregion
    }
}
